import React, { Key, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Tree, Card, Row, Col, Tag, Pagination, Table, Button } from "antd";
import {
  getHospitalDepartmentListRequest,
  getHosScheduleRuleRequest,
  findScheduleListRequest,
} from "@api/hospital/hospitalList";
import {
  hospitalDepartmentListType,
  bookingScheduleListType,
  findSCheduleListReturnType,
} from "@/api/hospital/model/hospitalListTypes";
export default function HospitalSchedule() {
  const navigate = useNavigate();
  const { hoscode } = useParams();

  //创建一个存储树形数据的状态，类型为返回的Schedule数据
  const [treeData, setTreeData] = useState<hospitalDepartmentListType>([]);
  //定义一个时间排班规则的当前页码
  const [page, setPage] = useState(1);
  //定义一个时间排班规则的每页条数
  const [limit, setLimit] = useState(3);
  //定义一个数据总数的类型
  const [total, setTotal] = useState(0);
  //定义当前选中的科室
  const [depCode, setDepCode] = useState("200040878");
  //定义当前科室的排班规则
  const [scheduleRule, setScheduleRule] = useState<bookingScheduleListType>([]);
  //定义一个初始化的时间状态
  const [workDate, setWorkDate] = useState("2022-04-28");
  //排班信息表格的状态
  const [sourceData, setSourceData] = useState<findSCheduleListReturnType>([]);

  //初始化请求获取树形数据，并将其设置给状态
  useEffect(() => {
    const getDepartmentList = async () => {
      const result = await getHospitalDepartmentListRequest(hoscode as string);
      // console.log(result);
      //将获取到的科室的数据交给state
      setTreeData(result);
    };
    getDepartmentList();
  }, []);

  //获取科室排班时间表规则
  useEffect(() => {
    const getScheduleRule = async () => {
      const result = await getHosScheduleRuleRequest({
        page,
        limit,
        hoscode: hoscode as string,
        depcode: depCode,
      });
      //设置时间排班列表
      setScheduleRule(result.bookingScheduleList);
      //定义一个数据总数的类型
      setTotal(result.total);
      //把数据中第一个时间交给wordDate这个状态的初始值
      setWorkDate(result.bookingScheduleList[0].workDate);
      // console.log(result);
    };
    getScheduleRule();
  }, [page, limit, depCode]);

  //获取医生的详细信息的事件
  useEffect(() => {
    const getFindScheduleList = async () => {
      const result = await findScheduleListRequest({
        hoscode: hoscode as string,
        depcode: depCode,
        workDate,
      });
      // console.log(result);

      setSourceData(result);
    };
    getFindScheduleList();
  }, [workDate, depCode]);

  //表格的字段
  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "可预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "挂号费（元）",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];

  //树形空间的样式
  const TreeStyle = {
    border: "1px solid #DDD",
    overflow: "auto",
    height: "480px",
  };
  //改变页码的事件回调函数
  const changePageHandle = (page: number, limit: number) => {
    setPage(page);
    setLimit(limit);
  };

  //切换tree的事件回调函数
  const treeSelectHandle = (depCodeArr: Key[]) => {
    setDepCode(depCodeArr[0] as string);
  };
  //点击选项的事件回调函数
  const scheduleRuleHandle = (workDate: string) => {
    return () => {
      // console.log(workDate);
      setWorkDate(workDate);
    };
  };

  return (
    <div>
      <Card>
        <p>选择:北京协和医院/多发性硬化专科门诊/2022-04-08</p>
        <Row gutter={20}>
          <Col span={5}>
            <Tree
              style={TreeStyle}
              //断言数据为数组，解决TS的报错，目前官方的解决方案
              treeData={treeData as []}
              //自定义数据字段名
              fieldNames={{ title: "depname", key: "depcode" }}
              //将树形控件的数据受控
              expandedKeys={["a4e171f4cf9b6816acdfb9ae62c414d7"]}
              onSelect={treeSelectHandle}
            />
          </Col>
          <Col span={19}>
            <div style={{ marginBottom: 20 }}>
              {/* 将获取到的时间表，拿去渲染 */}
              {scheduleRule.map((item) => {
                return (
                  <Tag
                    key={item.workDate}
                    color="green"
                    style={{ cursor: "pointer" }}
                    onClick={scheduleRuleHandle(item.workDate)}
                  >
                    <p>{item.workDate}</p>
                    <p>
                      {item.availableNumber}/{item.reservedNumber}
                    </p>
                  </Tag>
                );
              })}
            </div>
            {/* 分页器组件 */}
            <Pagination
              current={page}
              pageSize={limit}
              total={total}
              onChange={changePageHandle}
            />
            <Table
              style={{ marginTop: 20 }}
              columns={columns}
              bordered
              dataSource={sourceData}
              pagination={false}
              rowKey={"id"}
            />
            <Button
              style={{ marginTop: 20 }}
              type="default"
              onClick={() => {
                navigate(-1);
              }}
            >
              返回
            </Button>
          </Col>
        </Row>
      </Card>
    </div>
  );
}
